//
//  StatusListViewModel.swift
//  Weibo
//
//  Created by 李振兴 on 15/10/20.
//  Copyright © 2015年 李振兴. All rights reserved.
//

import Foundation
import SDWebImage

class StatusListViewModel {
     var statusList = [StatusViewModel]()
    func loadStatus(isPullup isPullup:Bool, finished:(isSuccess:Bool)->()){
        //下拉刷新
        let since_id = isPullup ? 0 : (statusList.first?.status.id ?? 0)
        //上拉刷新
        let max_id = isPullup ? (statusList.last?.status.id ?? 0) : 0
        NetWorkTools.sharedTools.loadStatus(since_id: since_id, max_id: max_id) { (result, error) -> () in
            if error != nil {
                print(error)
                finished(isSuccess: false)
                return
            }else{
                print(result)
                guard let array = result?["statuses"] as? [[String:AnyObject]] else{
                    print("数据格式错误")
                    finished(isSuccess: false)
                    return
                }
                //缓存到本地
                StatusDAL.saveCacheData(array)
                
                var dataList = [StatusViewModel]()
                for dict in array {
                    dataList.append(StatusViewModel(status: Status(dict: dict)))
                }
                print("刷新到 \(dataList.count) 条数据")
                if since_id > 0 {
                    self.statusList = dataList + self.statusList
                }else{
                    self.statusList += dataList
                }
                
                
                //finished(isSuccess: true)
                self.cacheSingleImage(dataList, finished: finished)
            }
        }
    }
    //缓存单张图片
    func cacheSingleImage(dataList:[StatusViewModel],finished:(isSuccess:Bool)->()){
        let group = dispatch_group_create()
        // 缓存数据长度
        var dataLength = 0
        for vm in dataList{
            if vm.thumbnailUrls?.count != 1{
                continue
            }
            let url = vm.thumbnailUrls![0]
                print("开始下载图像 \(url)")
            
            dispatch_group_enter(group)
            SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [SDWebImageOptions.RefreshCached, SDWebImageOptions.RetryFailed], progress: nil, completed: { (image, _, _, _, _) -> Void in
                // 单张图片下载完成 － 计算长度
                if let img = image,
                    let data = UIImagePNGRepresentation(img) {
                        
                        // 累加二进制数据的长度
                        dataLength += data.length
                }
                dispatch_group_leave(group)
            })
            
        }
        
            dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
                print("全部下载完成")
                //成功
                finished(isSuccess: true)
                print("缓存完成 \(dataLength / 1024) K")

                print(NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
)
        }
    }
}